<?php

declare(strict_types=1);

namespace app\shop\controller;

use app\shop\controller\Base;
use app\model\Column;
use think\facade\Request;
use app\model\Goods as GoodsMod;
use app\model\Shopcart;

/**
 * @name 商品类
 */
class Goods extends Base
{
    /**
     * @name 普通商品
     */
    public function goods()
    {
        if (request()->isPost()) {
            $param = Request::param();
            $w = [];

            if (isset($param['cid'])) {
                $w[] = ['a.cat_id', '=', $param['cid']];
            }
            if (isset($param['keywords']) && $param['keywords'] != '') {
                $w[] = ['a.title', 'like', '%' . $param['keywords'] . '%'];
            }
            if (empty($w)) {
                $w = "";
            }
            $list = GoodsMod::list($w, (int)$param['limit'], (int)$param['curr']);
            foreach ($list['data'] as $k => $v) {
                $v['sales'] = (int)$v['sales'] + (int)$v['virtual_sales'];
                $arr[] = $v;
            }
            return json(['code' => 0, 'msg' => '操作成功', 'data' => $arr, 'count' => $list['count']]);
        }
    }

    protected $middleware = [\app\shop\middleware\checkToken::class]; //单独使用

    /**
     * @name 加入购物车
     */
    public function goodscart()
    {
        if (request()->isPost()) {
            $data = request()->token;
            $param = Request::param();
            $find = Shopcart::find([['user_id', '=', $data['id']], ['goods_id', '=', $param['goods_id']]], 'id');
            if ($find) {
                return json(['code' => 2, 'msg' => '该商品已收藏']);
            }
            $param['user_id'] = $data['id'];
            $res = Shopcart::add($param);
            if ($res) {
                return json(['code' => 0, 'msg' => '添加成功']);
            } else {
                return json(['code' => 2, 'msg' => '添加失败']);
            }
        }
    }
}
